import { getInfo,getUserByIdDetail } from "@/api/user"
import { getToken, removeToken, setToken } from "@/utils/auth"
import { Message } from "element-ui"
import { login } from '@/api/user'
import { resetRouter } from "@/router"

//核心的配置项
export default {
  namespaced: true,
  state: {
    token:getToken()||'',
    userinfo:{}
  },
  mutations: {
    updateToken(state,token){
      state.token=token
      setToken(token)
    },
    delToken(state){
      state.token=''
      removeToken()
    },
    //更新详情
    updateUserInfo(state,info){
      state.userinfo=info
    },
    //清空用户信息、
    delUserInfo(state){
      state.userinfo=''
    }
  },
  actions: {
    async initToken(context,formDate){
      const res =await login(formDate)
      // console.log(res);
      if(res.code!==10000) return Message.error(res.message)
      Message.success(res.message)
      context.commit('updateToken',res.data)
    },
    async userInfo(context){
      try {
      //获取用户信息
      const res =await getInfo()
      // console.log(res,'res');
      //获取个人详情
      const info =await getUserByIdDetail(res.data.userId)
      context.commit('updateUserInfo',{...res.data,...info.data})
      //返回权限的信息
      return res.data.roles.menus
      } catch (error) {
        console.log(error);
      }
    },
    logout(context) {
      // 弹层询问，是否退出
      context.commit('delToken')
      context.commit('delUserInfo')
      //重置路由
      resetRouter()
    }

  }
}